<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
define('WXPAY_ROOT', $_SERVER["DOCUMENT_ROOT"] . '/wxpay/');
require_once WXPAY_ROOT."lib/WxPay.Api.php";
require_once WXPAY_ROOT.'lib/WxPay.Notify.php';
require_once WXPAY_ROOT.'log.php';

//初始化日志
$logHandler= new CLogFileHandler(WXPAY_ROOT."logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
Log::DEBUG("begin notify");
class PayNotifyCallBack extends WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($input);
        Log::DEBUG("query:" . json_encode($result));
        if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
            $out_trade_no=$result['out_trade_no'];//私有订单号，你就用这个订单号来进行你自己订单的各种更新吧
            $mch_id=$result['mch_id'];//商户号
            $total_fee=$result['total_fee'];//支付金额，出来的金额要除以100
            $transaction_id=$result['transaction_id'];//微信内部的订单流水号
            $openid=$result['openid'];//微信加密的用户身份识别,app支付的话其实意义不大了
            /*以下两行用做调试，会自动生成in_test.txt文件而且后期内容会自动追加到这个文件*/
            $fp = fopen('in_test.txt','a+');
            fwrite($fp,date("Y-m-d H:i:s").json_encode($result) . "|".$transaction_id." 成功了！rn");
            /**/
            return true;//这个很重要，微信的异步请求，当你执行完了你的内部处理以后给他返回true，微信就认为你的内部处理完成了，就不会再次请求你了，否则他会一直请求你这个文件，知道超时。
        }
        return false;
    }
     
    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        Log::DEBUG("call back:" . json_encode($data));
        $notfiyOutput = array();
         
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            return false;
        }
        $trade_status = $data['return_code'];
        $out_trade_no = $data['out_trade_no'];

        $p = array(
            'ordersid' => $out_trade_no,
            'status' => '0'
        );
        $row = jtable('mall_order')->get($p);
        if ($row['list']){
            $updata = array(
                'status' => '1',
                'pay_time' => time(),
                'post_str' => $this->createLinkString($data)
            );
            jtable('mall_order')->update($updata,array('ordersid'=>$out_trade_no));
            foreach ($row['list'] as $value) {
                $uid = $value['uid'];
                $goods_type = $value['goods_style'];
                if($goods_type == 'fictitious'){

                    $member = jsg_member_info($uid);
                    jtable('members')->update(array('extcredits2'=>($member['extcredits2']-$value['pay_gold'])),array('uid'=>$uid));
                    update_credits_by_action('convert', $uid);
                    update_credits_by_action('consume',$uid);
                    $starttime = strtotime(date('Y-m-d 00:00:00', time()));
                    $endtime = strtotime(date('Y-m-d 23:59:59', time()));
                    $where_arr = array(
                        'uid' => $uid,
                        'goods_style' => 'fictitious',
                        '>=@pay_time' => $starttime,
                        '<=@pay_time' => $endtime,
                        '>=@status' => 1,
                        '<=@status' => 2
                    );
                    $count = jtable('mall_order')->count($where_arr);
                    if($count >= 10){
                        update_credits_by_action('convert-ten',$uid);
                    }
                    $gifts = jtable('my_gifts')->info(array('uid'=>$uid,'gid'=>$value['goods_id']));
                    if(is_array($gifts)){
                        $savedata = array(
                            'uid'=>$uid,
                            'gid'=>$value['goods_id'],
                            'num' => $gifts['num'] + $value['goods_num'],
                        );
                        jtable('my_gifts')->update($savedata,array('uid'=>$uid,'gid'=>$value['goods_id']));
                    }else{
                        $savedata = array(
                            'uid'=>$uid,
                            'gid'=>$value['goods_id'],
                            'num' => $value['goods_num'],
                        );
                        jtable('my_gifts')->insert($savedata);
                    }
                }else{
                    update_credits_by_action('buy', $uid);
                    update_credits_by_action('consume',$uid);
                    $starttime = strtotime(date('Y-m-d 00:00:00', time()));
                    $endtime = strtotime(date('Y-m-d 23:59:59', time()));
                    $where_arr = array(
                        'uid' => $uid,
                        'goods_style' => 'entity',
                        '>=@pay_time' => $starttime,
                        '<=@pay_time' => $endtime,
                        '>=@status' => 1,
                        '<=@status' => 2
                    );
                    $count = jtable('mall_order')->count($where_arr);
                    if($count >= 5){
                        update_credits_by_action('buy-five',$uid);
                    }
                }
            }

        }else{
            $recharge_p = array(
                'ordersid' => $out_trade_no,
                'pay_status' => '0'
            );
            $recharge = jtable('recharge_log')->info($recharge_p);
            if(is_array($recharge)){
                $updata = array(
                    'pay_status' => 1,
                    'pay_time' => date('Y-m-d H:i:s', time())
                );
                jtable('recharge_log')->update($updata,array('ordersid'=>$out_trade_no));
                $uid = $recharge['r_uid'];
                $member = jsg_member_info($uid);
                jtable('members')->update(array('extcredits2'=>($member['extcredits2']+$recharge['get_coin'])),array('uid'=>$uid));
                update_credits_by_action('recharge', $uid);
                update_credits_by_action('recharging',$uid);
                $starttime = date('Y-m-d 00:00:00', time());
                $endtime = date('Y-m-d 23:59:59', time());
                $where_arr = array(
                    'r_uid' => $uid,
                    '>=@pay_time' => $starttime,
                    '<=@pay_time' => $endtime,
                    'pay_status' => '1'
                );
                $count = jtable('recharge_log')->count($where_arr);
                if($count >= 5){
                    update_credits_by_action('recharge-five',$uid);
                }
            }
        }
        return true;
    }
    function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
                $arg.=$key."=".$val."&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);

        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

        return $arg;
    }
} 